import cookiesUtil from 'js-cookie';
import queryString from 'query-string';
import _ from 'lodash';
import * as store from './storage';

/* 用户信息存储key*/
const EnumLoginInfoKey = '__login_info__';

class Auth {
  constructor() {
    // 登录成功的cookie key
    // this.loginSuccessCookieKey = window.ENV.login.cookieKey;
  }

  /**
   * 验证是否登录
   * @returns {boolean}
   */
  isLogin() {
    // return window.ENV.login.isCheckLogin ? cookiesUtil.get(EnumLoginInfoKey) : true;
    return window.ENV.login.isCheckLogin ? !_.isEmpty(this.getLoginInfo()) : true;
  }

  /**
     * 登录成功重定向
     */
  loginSuccessRedirect() {
    const urlParams = queryString.parse(window.location.search);
    let redirectUrl = window.ENV.login.defaultRedirectUrl;

    if (_.isPlainObject(urlParams) && 'redirect_uri' in urlParams) {
      redirectUrl = decodeURIComponent(urlParams['redirect_uri']);
    }
    window.location.href = redirectUrl;
  }

  /**
     * 保存登录信息
     * @param loginInfo
     */
  setLoginInfo(loginInfo) {
    store.setStorage(EnumLoginInfoKey, loginInfo);
  }

  /**
     * 获取登录信息
     * @return {*}
     */
  getLoginInfo() {
    return store.getStorage(EnumLoginInfoKey) || {};
  }

  /**
   * 移除登录信息
   */
  removeLoginInfo() {
    store.removeStorage(EnumLoginInfoKey);
  }

  // -------以下是权限校验-------

  /**
   * 校验权限
   * @param identity
   * @return {boolean}
   */
  can = (identity) => {
    const { isAdmin, menuPermissions } = this.getLoginInfo() || {};
    if (!isAdmin && !_.isEmpty(menuPermissions)) return menuPermissions.indexOf(identity) !== -1;
    return true;
  };

    /**
     * 组件标签校验权限
     * @param identity
     * @param children
     * @return {null}
     * @constructor
     */
    Vcan = ({ identity, children }) => (this.can(identity) ? children : null)
}

export default new Auth();
